<template>
  <div class="announcement-page">
    <!-- 上部：公告发布栏 -->
    <el-card class="publish-card" v-if="isAdmin">
      <template #header>
        <h3>发布校园公告</h3>
      </template>

      <el-form
        ref="formRef"
        :model="publishForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="publishForm.title"
            placeholder="请输入公告标题"
            maxlength="100"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="publishForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="publishLoading"
            @click="handlePublish"
          >
            发布公告
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 下部：公告展示区 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <h3>校园公告</h3>
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索公告标题"
            clearable
            style="width: 300px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </template>

      <div v-loading="loading" class="announcement-list">
        <el-empty v-if="!loading && announcementList.length === 0" description="暂无公告" />

        <div
          v-for="announcement in announcementList"
          :key="announcement.id"
          class="announcement-item"
          @click="handleViewDetail(announcement.id)"
        >
          <div class="item-header">
            <h4 class="item-title">{{ announcement.title }}</h4>
            <div class="item-meta">
              <el-icon><User /></el-icon>
              <span>{{ announcement.publisherName }}</span>
              <el-divider direction="vertical" />
              <el-icon><Clock /></el-icon>
              <span>{{ formatDate(announcement.createTime) }}</span>
              <el-divider direction="vertical" />
              <el-icon><View /></el-icon>
              <span>{{ announcement.viewCount }}</span>
            </div>
          </div>
          <div class="item-content">
            {{ truncateContent(announcement.content) }}
          </div>
          <div class="item-footer">
            <el-button type="primary" size="small" text>查看详情</el-button>
            <el-button
              v-if="canDelete(announcement)"
              type="danger"
              size="small"
              text
              @click.stop="handleDelete(announcement.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 公告详情对话框 -->
    <AnnouncementDetailDialog
      v-model="detailVisible"
      :announcement-id="currentAnnouncementId"
      @refresh="getAnnouncementList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, User, Clock, View } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  reqPublishAnnouncement,
  reqGetAnnouncementList,
  reqDeleteAnnouncement
} from '@/api/announcement'
import type { AnnouncementItem } from '@/api/announcement/type'
import AnnouncementDetailDialog from './components/AnnouncementDetailDialog.vue'
import useUserStore from '@/stores/modules/user'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 判断是否为管理员
const isAdmin = computed(() => {
  return (
    userStore.buttons?.includes('announcement:publish')
  )
})

// 发布表单
const formRef = ref<FormInstance>()
const publishForm = reactive({
  title: '',
  content: ''
})

const formRules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度为2-100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度为10-2000个字符', trigger: 'blur' }
  ]
})

const publishLoading = ref(false)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  keyword: ''
})

// 公告列表
const announcementList = ref<AnnouncementItem[]>([])
const total = ref(0)
const loading = ref(false)

// 详情对话框
const detailVisible = ref(false)
const currentAnnouncementId = ref<number>(0)

// 发布公告
const handlePublish = async () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }

    publishLoading.value = true

    try {
      const result: any = await reqPublishAnnouncement(publishForm)

      if (result.code === 200) {
        ElMessage.success('发布成功！')
        handleReset()
        // 刷新列表
        queryParams.page = 1
        getAnnouncementList()
      } else {
        ElMessage.error(result.message || '发布失败')
      }
    } catch (error: any) {
      console.error('发布失败:', error)
      ElMessage.error(error.message || '发布失败')
    } finally {
      publishLoading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  publishForm.title = ''
  publishForm.content = ''
}

// 获取公告列表
const getAnnouncementList = async () => {
  if (loading.value) return
  loading.value = true

  try {
    const result: any = await reqGetAnnouncementList(queryParams)
    if (result.code === 200) {
      announcementList.value = result.data.records || []
      total.value = result.data.total || 0
    } else {
      ElMessage.error(result.message || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getAnnouncementList()
}

// 分页处理
const handlePageChange = () => {
  getAnnouncementList()
}

const handleSizeChange = () => {
  queryParams.page = 1
  getAnnouncementList()
}

// 查看详情
const handleViewDetail = (id: number) => {
  currentAnnouncementId.value = id
  detailVisible.value = true
}

// 删除公告
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const result: any = await reqDeleteAnnouncement(id)
      if (result.code === 200) {
        ElMessage.success('删除成功')
        getAnnouncementList()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 判断是否可以删除
const canDelete = (announcement: AnnouncementItem) => {
  // 管理员或发布者本人可以删除
  return isAdmin.value || announcement.publisherName === userStore.username
}

// 截断内容
const truncateContent = (content: string) => {
  if (content.length > 100) {
    return content.substring(0, 100) + '...'
  }
  return content
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

// 页面加载时获取列表
onMounted(() => {
  getAnnouncementList()
})
</script>

<style scoped lang="scss">
.announcement-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.publish-card {
  margin-bottom: 20px;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.list-card {
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.announcement-list {
  min-height: 300px;
}

.announcement-item {
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

  &:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
    transform: translateY(-2px);
  }

  &:last-child {
    margin-bottom: 0;
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    .item-title {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .item-meta {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 13px;
      color: #909399;

      .el-icon {
        font-size: 14px;
      }
    }
  }

  .item-content {
    margin-bottom: 15px;
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
  }

  .item-footer {
    display: flex;
    gap: 10px;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .announcement-page {
    padding: 10px;
  }

  .list-card .list-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;

    .el-input {
      width: 100% !important;
    }
  }

  .announcement-item .item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
